package com.nervenets.general.aspect.validate.validator;

import com.nervenets.general.aspect.validate.EntityNotNull;
import com.nervenets.general.hibernate.DomainObject;
import com.nervenets.general.service.BaseService;
import com.nervenets.general.utils.SpringContextHolder;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

public class EntitiesNotNullValidator implements ConstraintValidator<EntityNotNull, List<Long>> {
    private BaseService<? extends DomainObject> service;

    @Override
    public void initialize(EntityNotNull entityNotNull) {
        this.service = SpringContextHolder.getBean(entityNotNull.entityService());
    }

    @Override
    public boolean isValid(List<Long> ids, ConstraintValidatorContext context) {
        if (null == ids || ids.isEmpty() || null == this.service) return true;
        try {
            return ids.stream().allMatch(id -> service.existsById(id));
        } catch (Exception e) {
            return false;
        }
    }
}
